from pyecharts import Bar
from lib.utility.date import *
from lib.utility.path import *
import re
from pyecharts import Line
from pyecharts import Bar
from pyecharts import Pie
from pyecharts import Grid
from  pyecharts import Page
date_string = get_date_string()
print('Today date is: %s' % date_string)
city = 'nc'
today_path = create_date_path("loupan", city, date_string)
csv_file = today_path + "/{0}.csv".format(city)
data ={}
f = open(csv_file,'rt',encoding="UTF-8")
line = f.readline()
while line:
    line = f.readline()
    tmp = line.split(',')
    if len(tmp) >= 2:
        data[tmp[1]] = tmp
f.close()

def createone(newData):
    # print(newData)
    path = today_path + "/zoushi/{0}.html".format(newData['id'])
    line = Line(newData['name'])
    # createone(newData['zoushi']['name'], newData['zoushi']['data1'], newData['zoushi']['data2'], newData['zoushi']['id'])
    line.add('价格（元）', newData['zoushi']['data1'], newData['zoushi']['data2'])
    line.render(path)
def getValue(index,list):
    if list is not None and len(list) > index:
        return list[index]
    return ''

def getzoushi(value,id,name):
    if len(value) > 2:
        dict = {}
        dict['data1'] =[]
        dict['data2'] =[]
        dict['id'] = id
        dict['name'] = name
        ckpc = int(len(value) - 2)
        for i in range(ckpc):
            pricedata = value[i + 2].split(':')
            if len(pricedata) >=2:
                dict['data1'].append(pricedata[0])
                dict['data2'].append(str(pricedata[1]).replace('元', ''))
        return dict
    return {}
def getQu(strv):
    p =r'^\[.*\]'
    pattern1 = re.compile(p)  # 我们在编译这段正则表达式
    matcher1 = re.search(pattern1,strv)  # 在源文本中搜索符合正则表达式的部分
    if matcher1 is not None and matcher1.group is not None:
        return matcher1.group(0).replace('[', '').replace(']', '')
    else:
        return ''
newDataN ={}
test = True
idx = 0;
for key in data:
    newData ={}
    value = data[key]
    newData['id'] = idx
    idx = idx + 1
    # print(value)
    newData['date'] = getValue(0, value)
    newData['name'] = getValue(1, value)
    newData['price'] = getValue(2, value)
    newData['status'] = getValue(3, value)
    newData['qu'] = getQu(getValue(4, value))
    newData['address'] = getValue(4, value)
    newData['huxing'] = getValue(5, value).split(' ')

    count = len(value)
    if count >= 7:
        newData['news'] = getValue(count - 1, value)

    newData['ckPrice'] = getValue(count - 5,value).split('  ')
    newData['ckPrice1'] = getValue(count - 4,value).split('  ')
    newData['ckPrice2'] = getValue(count - 3,value).split('  ')
    newData['zoushi'] = getzoushi(newData['ckPrice'], newData['id'],newData['name'])
    newData['zoushi1'] = getzoushi(newData['ckPrice1'], newData['id'],newData['name'])
    newData['zoushi2'] = getzoushi(newData['ckPrice2'], newData['id'],newData['name'])
    # print(newData)
    newDataN[newData['name']] = newData
    # break
# print(newDataN)
csv_file = today_path + "/{0}.html".format('zoushi')
qu =['经开区','南昌县','红谷滩区','青山湖区','湾里区','新建区','高新开发区','象湖新城','朝阳新城','青云谱区','西湖区','桑海开发区','九龙湖新城']
newdict ={}
newdictp ={}
newallp ={}
for key in newDataN:
    itemData = newDataN[key]
    if 'qu' in itemData.keys():
        for i in range(len(qu)):
            if itemData['qu'] == qu[i]:
                if 'zoushi2'in itemData.keys():
                    newdictp[qu[i]] = itemData['zoushi2']
                if qu[i] in newdict.keys():
                    newdict[qu[i]].append(itemData)
                else:
                    newdict[qu[i]] =[]
                    newdict[qu[i]].append(itemData)

# print(newdict)
# print(newdictp)
with open(csv_file, "w", encoding='utf-8') as f:
    f.write('<!DOCTYPE html>\n<html>\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>"房价走势"</title>\n</head>\n<body>\n')
    for key in newDataN:
        newData = newDataN[key]
        # print(newData)
        # createone(newData);
        if 'zoushi' in newData.keys():
            # print(newData['zoushi'])
            if len(newData['zoushi']) > 3:
                f.write('<p><a href ="./zoushi/{0}.html">{1}</a></p>'.format(newData['zoushi']['id'], newData['zoushi']['name'] + '\n'))
                createone(newData)
                break
    f.write('\n</body>\n</html>')
    f.close()

page = Page()
line = Line("南昌房价走势")
for key in newdictp:
    if 'data1' in newdictp[key].keys() and 'data2' in newdictp[key].keys():
        line.add(key, newdictp[key]['data1'], newdictp[key]['data2'],yaxis_formatter="元/㎡",yaxis_min = 3000)
page.add(line)
# path = today_path + "/{0}.html".format("ncgqzs")
# print(path)
# line.render(path)

for key in newdict:
    newdictp123 = newdict[key]
    grid = Grid(width = 1000,height = 800)
    # line = Line(key + "房价走势",title_top = 'top',title_pos ='center',width =800,height = 800)
    line = Line(width=1000, height=800, title=key + "房价走势", title_pos="0%")
    for i in range(len(newdictp123)):
        newdictp1234 = newdictp123[i];
        # print(type(newdictp1234))
        if 'zoushi' in newdictp1234.keys():
            newdictp12345 = newdictp1234['zoushi']
            if 'data1' in newdictp12345.keys() and 'data2' in newdictp12345.keys():
                line.add(newdictp1234['name'], newdictp12345['data1'], newdictp12345['data2'],legend_pos="0%",legend_orient="horizontal",legend_top="10%",yaxis_formatter="元/㎡",yaxis_min = 3000)
    grid.add(line, grid_top="30%")
    page.add(grid)
path = today_path + "/{0}.html".format("ncgqzs1")
print(path)
page.render(path)




